package edu.neu.ecommerceplatform.controller;


import edu.neu.ecommerceplatform.dto.CreateUserRequest;
import edu.neu.ecommerceplatform.dto.UpdateNameRequest;
import edu.neu.ecommerceplatform.model.User;
import edu.neu.ecommerceplatform.service.UserService;
import jakarta.servlet.Servlet;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("api/user")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        return ResponseEntity.ok(user);
    }

    @GetMapping("/name/{name}")
    public ResponseEntity<User> getUserByName(@PathVariable String name){
        //System.out.println(userService.getUserByName(name));
        User user = userService.getUserByName(name);
        return ResponseEntity.ok(user);
    }
    @GetMapping("/phone/{phone_number}")
    public ResponseEntity<User> getUserByPhone(@PathVariable String phone_number){
        User user = userService.getUserByPhone(phone_number);
        return ResponseEntity.ok(user);
    }

    @PutMapping("/phone/{phone_number}/name")
    public ResponseEntity<User> updateUserByPhone(@PathVariable String phone_number, @Valid @RequestBody UpdateNameRequest updateNameRequest){
        User user = userService.updateNameByPhone(phone_number,updateNameRequest.getName());
        return ResponseEntity.ok(user);
    }

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody CreateUserRequest createUserRequest){
        User user = userService.createUser(createUserRequest);

        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(user.getId())
                .toUri();
        return ResponseEntity.created(location).body(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/product/{productId}/buyers")
    public ResponseEntity<List<User>> getUsersByProductId(@PathVariable Integer productId) {
        List<User> users = userService.getUsersByProductId(productId);
        return ResponseEntity.ok(users);
    }
}
